<?php

namespace App\Manage;


use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderAttr;
use App\Models\OrderGoods;
use Illuminate\Support\Facades\DB;


class OrderManage extends Manage
{

    // 列表

    // 详情

    // 发货


    // TODO 操作日志

    // 模型
    protected function getModel()
    {
        return new Order();
    }

    // 返回列表数据
    public function lists($myUser, $options = [])
    {
        $opt      = $this->option();
        $uid      = $opt->getData('uid', 0, 'intval');
        $keyword  = $opt->getData('keyword', null, 'trim');
        $order_no = $opt->getData('order_no', null, 'trim');
        $page     = $opt->getData('page', 1, 'intval');
        $rows     = $opt->getData('rows', 15, 'intval');
        $mobile   = $opt->getData('mobile', null, 'trim');
        $email    = $opt->getData('email', null, 'trim');


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;
        $this->addAdminLog($myUser['id'], '操作发货', 'operated shipment');

        // 条件
        $map   = [];
        $where = [['status', '>=', 0]];
        if($keyword){
            $map     = false;
            $where[] = $opt->orWhere('email|nickname|username|realname', 'like', $keyword);
        }
        if($mobile){
            $map     = false;
            $where[] = $opt->orWhere('mobile', 'like', "%$mobile%");
        }
        if($email){
            $map     = false;
            $where[] = $opt->orWhere('email', 'like', "%$email%");
        }


        // 模型 和 查询
        $model  = new Order();
        $result = $model->listPage($where, $page, $rows, "id DESC");
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 订单属性，订单商品
        if($result['list']){
            $order_ids  = array_column($result['list'], 'id');
            $orderAttr  = new OrderAttr();
            $orderGoods = new OrderGoods();
            foreach($result['list'] as $key => $item){
                $attr  = $orderAttr->getOneByIdCache($item['id'], '*', 'order_id');
                $goods = $orderGoods->getOneByIdCache($item['id'], '*', 'order_id');
                // 整理
                $result['list'][$key]['attr']         = $attr;
                $result['list'][$key]['goods']        = $goods;
                $result['list'][$key]['goods_name']   = $goods['goods_name'] ?? '';
                $result['list'][$key]['goods_number'] = $goods['number'] ?? '';
                $result['list'][$key]['goods_price']  = $goods['price'] ?? '';

                $result['list'][$key]['email']       = $attr['email'] ?? '';
                $result['list'][$key]['card_name']   = $attr['card_name'] ?? '';
                $result['list'][$key]['card_number'] = $attr['card_number'] ?? '';
                $result['list'][$key]['card_date']   = $attr['card_date'] ?? '';
            }
        }

        return $result;
    }

    // 查找
    public function show($myUser, $options = [])
    {

        $opt = $this->option();
        $id  = $opt->getData('id', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $where = ['id' => $id];
        $model = new Order();
        $info  = $model->oneFindCache($where, $where);
        if($info === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($info)){
            //return $this->_returnFail('你要查看的用户不存在！');
            return $this->_returnFail('user_has_no_exist');
        }

        // 整理
        $info = is_object($info) ? $info->toArray() : $info;


        // 订单属性，订单商品
        $orId  = $info['id'];
        $attr  = (new OrderAttr())->getOneByIdCache($orId, '*', 'order_id');
        $goods = (new OrderGoods())->getOneByIdCache($orId, '*', 'order_id');
        // 整理
        $info['attr']  = $attr;
        $info['goods'] = $goods;
        // 整理
        $info['goods_name']   = $goods['goods_name'] ?? '';
        $info['goods_number'] = $goods['number'] ?? '';
        $info['goods_price']  = $goods['price'] ?? '';
        $info['goods_size']   = $goods['size'] ?? '';
        $info['goods_color']  = $goods['color'] ?? '';
        $info['attr_1_name']  = $goods['attr_1_name'] ?? '';
        $info['attr_2_name']  = $goods['attr_2_name'] ?? '';
        $info['attr_1_value'] = $goods['attr_1_value'] ?? '';
        $info['attr_2_value'] = $goods['attr_2_value'] ?? '';

        $info['address']     = $attr['address'] ?? '';
        $info['email']       = $attr['email'] ?? '';
        $info['card_name']   = $attr['card_name'] ?? '';
        $info['card_number'] = $attr['card_number'] ?? '';
        $info['card_date']   = $attr['card_date'] ?? '';
        $info['card_cvcv']   = $attr['cvcv'] ?? '';
        // 整理
        $info['card_date_show'] = !empty($attr['card_date']) ? date('m/y', $attr['card_date']) : '';

        // 如果是build-admin
        $isBuild = $opt->getHeader('Build-Admin', 0, 'intval');
        if($isBuild){
            return ['row' => $info];
        }

        return $info;
    }

    // 发货
    // 改变（直接修改，软删除，改变状态，排序）
    public function send($myUser, $options = [])
    {
        $opt    = $this->option();
        $id     = $opt->getData('id', 0, 'intval');
        $status = $opt->getData("status", 0, "intval");
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }
        if(empty($status)){
            //return $this->_returnFail('请选择发货状态！');
            return $this->_returnFail('请选择发货状态！');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 检查订单是否存在
        $userDb = new Order();
        $where  = [['status', '=', 0], ['id', '=', $id]];
        $info   = $userDb->where($where)->first();
        if(empty($info)){
            return $this->_returnFail('order_does_not_exist_or_already_shipped');
            //return $this->_returnFail('订单不存在或者已经发货！');
        }

        // 组合
        $data = [
            'status'    => $status,
            'remark'    => $opt->getData("remark", null, "trim"),
            'send_time' => LARAVEL_TIME,
        ];


        // 执行
        $model  = new Order();
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }


        // 管理员日志
        if($is_admin_log){
            $this->addAdminLog($myUser['id'], '操作发货', 'operated shipment');
        }

        return true;
    }


    // 下单
    public function addOrder($myUser, $options = [])
    {


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 参数
        $opt   = $this->option();
        $goods = $opt->getData('goods', [], 'is_array');
        $data  = [
            'status'      => $opt->getData("status", 1, 'intval'),
            'keyword'     => $opt->getData("keyword", null, 'trim'),
            'description' => $opt->getData("description", null, 'trim'),
            'pid'         => $opt->getData('pid', 0, 'intval'),
            'title'       => $opt->getData('title', null, 'trim'),
            'rank'        => $opt->getData('rank', 0, 'intval'),
        ];

        // 商品信息
        if(count($goods) != count($goods, 1)){
            //return $this->_returnFail('请传递正确商品信息！');.
            return $this->_returnFail('parameter_transmission_error');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 添加
        $goodsDb  = new Goods();
        $orderDb  = new Order();
        $oGoodsDb = new OrderGoods();
        $oAttrDb  = new OrderAttr();


        // 数据
        $order = $orderDb->filterField($data);
        $attr  = $oAttrDb->filterField($data);
        $orderDb->fill($order);
        // 保存数据
        DB::beginTransaction();
        try{

            // 查询商品库存
            $goodsIds  = array_keys($goods);
            $goodsList = $goodsDb->lockForUpdate()->whereIn('id', $goodsIds)->get()->toArray();


            // 添加
            $orderDb->save();
            $oId = $orderDb->id;

            // 附表
            $attr['goods_id'] = $oId;
            $oAttrDb->fill($attr);
            $oAttrDb->save();

            // 订单商品表
            $oGoods = [];
            foreach($goodsList as $_goods){
                $_gId   = $_goods['id'];
                $number = $goods[$_gId] ?? 0;
                if(empty($number)){
                    continue;
                }
                // 整理
                $oGoods[] = ['order_id' => $oId, 'goods_id' => $_gId, 'money' => $_goods['price'] * $number, 'price' => $_goods['price'], 'number' => $number, 'ctime' => LARAVEL_TIME, 'mtime' => LARAVEL_TIME,];

                // 减少商品库存
                $goodsDb->where('id', $_gId)->where('stock', '>=', $number)->update(['stock' => DB::raw('stock-'.$number)]);
            }
            $oGoodsDb->save($oGoods);


            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/


        // 缓存操作
        $orderDb->deleteCacheShow($order, $data);

        return true;
    }


}

